

const koa = require('koa')
const router = require('koa-router')()
const jwt = require('jsonwebtoken')
const jweAuth = require('koa-jwt')
//秘钥
const secret = "it's a secret jjk"

//跨域问题
// const cors = require('koa2-cors')
const koaBody = require("koa-body");
const static = require('koa-static')



const db = require("./lib/db");
const { getDB } = require('./lib/db');

db.initDB();

const fs = require("fs");
const path = require("path");

//去除密码再返回 
const { resetData } = require('./lib/resetData.js')




const app = new koa()
app.keys = ['some secret']
app.use(static(__dirname + '/'))
app.use(
    koaBody({
        multipart: true
    })
);


//名字是否被注册
router.get('/checkname/:username?', async ctx => {
    const username = ctx.request.params.username
    const [row] = await getDB().execute(`SELECT * FROM userlist WHERE username=? limit 1`, [username])
    if (row.length === 1) {
        ctx.body = {
            message: '该用户名已被注册',
            state: 201
        }
    }
    else {
        ctx.body = {
            message: '该用户名可用',
            state: 200
        }
    }


})



router.post("/login", async ctx => {
    const { body } = ctx.request

    const { username, password } = body

    console.log(username, 'username');
    const [row] = await getDB().execute(`SELECT * FROM userlist WHERE username=? limit 1`, [username])
    if (row.length) {
        console.log(row);




        if (row[0].password === password) {
            console.log(username);
            ctx.body = {
                message: "登录成功",
                state: 200,
                user: username,
                //生成token，返回给客户端
                token: jwt.sign({
                    data: username,
                    //设置过期时间，单位为秒
                    // exp:Math.floor(Date.now()/1000)+60*60
                }, secret)

            }

        } else {
            ctx.body = {
                message: "登录失败",
                state: 201,

            }
        }

    } else {

        ctx.body = {
            message: "登录失败,用户名不存在",
            state: 201,

        }
    }


  

})
//测试用的
router.get(
    "/getUser-token",
    //验签
    jweAuth({ secret }),
    async ctx => {
        // console.log(ctx.state);


        // console.log(ctx.state.user.data,'username');

        ctx.body = {
            row,
            message: "获取数据成功",
            userinfo: ctx.state.user.data
        }
        /**
         * {"message":"获取数据成功","userinfo":"test"}
         */
    }
)

router.get('/users/:query?',
    jweAuth({ secret }),
    async ctx => {
        //ctx.state可以获取到加签时的数据
        // console.log(ctx.state.user.data, 'username')


        const queryobj = JSON.parse(ctx.query.query)
        console.log(queryobj.query);
        sql = `SELECT * FROM userlist `
        const res = await getDB().execute(sql)
        const total = res[0].length
        if (queryobj.query) {
            sql += " WHERE username LIKE ? LIMIT ?,?";
            const [row] = await getDB().execute(sql, ["%" + queryobj.query + "%", String(queryobj.pagenum), String(queryobj.pagesize)])

            ctx.body = { data: resetData(row), total }
        } else {
            sql += " LIMIT ?,?";
            const [row] = await getDB().execute(sql, [String(queryobj.pagenum), String(queryobj.pagesize)])
            ctx.body = { data: resetData(row), total }
        }


    })
//添加用户
router.post('/users',

    async ctx => {
        console.log(ctx.request.body);

        res = ctx.request.body
        const sql = `INSERT INTO userlist (username,password) VALUES  (?,?)`;
        const [rows] = await getDB().execute(sql, [res.username, res.password]);
        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = {message:"添加成功",
        state:200
        
        }
         
        } else {
            ctx.body = {message:"添加失败",
            state:201
        }
    }
    })

router.delete('/users/:id',
    jweAuth({ secret }),
    async ctx => {
        const sql = `DELETE FROM userlist WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.params.id]);
        console.log(rows);
        ctx.body = 'ok'
    })
//修改时获取单个用户
router.get('/user/:id',
    jweAuth({ secret }),
    async ctx => {
        console.log(ctx.params.id);
        const sql = `SELECT * FROM userlist WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.params.id]);

        ctx.body = { data: rows }
    })

router.put('/users/:id',
    jweAuth({ secret }),
    async ctx => {
        const sql = `UPDATE userlist SET mobile=? WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.request.body.mobile, ctx.params.id]);
        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = "修改成功";
        } else {
            ctx.body = "修改失败";
        }
    })

//角色
router.get('/roles',
    jweAuth({ secret }),
    async ctx => {
        const sql = `SELECT * FROM rolelist `
        const [rows] = await getDB().execute(sql);
        console.log(rows);
        ctx.body = rows
    })


router.get('/roles/:id',
    jweAuth({ secret }),
    async ctx => {
        const sql = `SELECT * FROM rolelist WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.params.id]);
        console.log(rows);
        ctx.body = { data: rows }
    })


router.delete('/roles/:id',
    jweAuth({ secret }),
    async ctx => {
        const sql = `DELETE FROM rolelist WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.params.id]);
        console.log(rows);
        ctx.body = { data: '删除成功' }
    })



router.put('/roles',
    jweAuth({ secret }),
    async ctx => {

        const { roleinfo } = ctx.request.body
        console.log(roleinfo);
        const sql = `UPDATE rolelist SET name=? ,des=?  WHERE id=? `
        const [rows] = await getDB().execute(sql, [roleinfo.name, roleinfo.des, roleinfo.id])

        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = { data: "修改成功" }
        } else {
            ctx.body = { data: "修改失败" }
        }

    })

router.put('/roles/right',
    jweAuth({ secret }),
    async ctx => {

        const { id, Uright } = ctx.request.body

        const sql = `UPDATE rolelist SET Uright=?  WHERE id=? `
        const [rows] = await getDB().execute(sql, [Uright, id])

        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = { data: "修改成功" }
        } else {
            ctx.body = { data: "修改失败" }
        }

    })


router.put('/users/:id/role',
    jweAuth({ secret }),
    async ctx => {
        console.log(ctx.request.body.managername, ctx.params.id);
        const sql = `UPDATE userlist SET managername=? WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.request.body.managername, ctx.params.id]);
        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = "修改成功";
        } else {
            ctx.body = "修改失败";
        }
    })

//获取权限
router.get('/right',
    jweAuth({ secret }),
    async ctx => {
        const sql = `SELECT * FROM rightlist`
        const [rows] = await getDB().execute(sql)
        ctx.body = { data: rows }
    })


//添加角色
router.post('/roles',
    jweAuth({ secret }),
    async ctx => {
        console.log(ctx.request.body);
        res = ctx.request.body
        const right = res.checkedUright
            .map((item) => Number(item))
            .sort((a, b) => a - b);
        var Uright = String(right)
        if (Uright === '') {
            Uright = 0
        }


        const sql = `INSERT INTO rolelist (name,des,Uright) VALUES  (?,?,?)`;
        const [rows] = await getDB().execute(sql, [res.name, res.des, Uright]);
        console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = "添加成功";
        } else {
            ctx.body = "添加失败";
        }
    })


//用户状态
router.put('/users/:id/Ustate/:Ustate',
    jweAuth({ secret }),
    async ctx => {
        console.log(ctx.params.Ustate, ctx.params.id);

        const sql = `UPDATE userlist SET Ustate=? WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.params.Ustate, ctx.params.id]);
        // console.log(rows.affectedRows);
        if (rows.affectedRows === 1) {
            ctx.body = "修改成功";
        } else {
            ctx.body = "修改失败";
        }
    })

//获取轮播图
router.get('/activity',
    jweAuth({ secret }),
    async ctx => {
        const sql = `SELECT * FROM activity`
        const [rows] = await getDB().execute(sql)
        ctx.body = { data: rows }
    })



//
router.post('/activity/upload',
    jweAuth({ secret }),
    async ctx => {

        const { img } = ctx.request.files;

        //保存到本地
        const uploadPath = '/upload/' + Date.now() + "_" + img.name
        saveImgToUpload(img, uploadPath)



        const url = 'http://localhost:7777' + uploadPath
        const sql = `insert into activity (url) value (?)`
        const [rows] = await getDB().execute(sql, [url])
        if (rows.affectedRows === 1) {
            ctx.body = "上传成功";
        } else {
            ctx.body = "上传失败";
        }

    })

router.delete('/activity/:id',
    jweAuth({ secret }),
    async ctx => {
        const sql = `DELETE FROM activity WHERE id=?`
        const [rows] = await getDB().execute(sql, [ctx.params.id]);
        console.log(rows);
        ctx.body = { data: '删除成功' }
    })

//图片保存到本地的方法
function saveImgToUpload(img, uploadPath) {
    const readStream = fs.createReadStream(img.path);
    const savePath = path.join(__dirname, uploadPath);
    const writeStream = fs.createWriteStream(savePath);
    readStream.pipe(writeStream);
}

app.use(router.routes())
app.listen(7777, () => { console.log('serve built') })

